package cn.lyyb2001.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.lyyb2001.admin.pojo.dto.UserAuthDTO;
import cn.lyyb2001.admin.pojo.entity.SysUser;
import cn.lyyb2001.admin.pojo.entity.SysUserRole;
import cn.lyyb2001.admin.pojo.vo.UserVO;
import cn.lyyb2001.admin.service.ISysPermissionService;
import cn.lyyb2001.admin.service.ISysUserRoleService;
import cn.lyyb2001.admin.service.ISysUserService;
import cn.lyyb2001.common.model.Result;
import cn.lyyb2001.common.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/users")
@Slf4j
public class UserController {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysUserRoleService sysUserRoleService;
    @Resource
    private ISysPermissionService iSysPermissionService;
    @Resource
    private PasswordEncoder passwordEncoder;

    @GetMapping
    public Result<IPage<SysUser>> list(Page<SysUser> page, String nickname, String mobile, Integer status, Long deptId) {
        SysUser user = new SysUser();
        user.setNickname(nickname);
        user.setMobile(mobile);
        user.setStatus(status);
        user.setDeptId(deptId);
        IPage<SysUser> result = sysUserService.list(page, user);
        return Result.success(result);
    }

    @GetMapping("/username/{username}")
    public Result<UserAuthDTO> getUserByUsername(@PathVariable String username) {
        return Result.success(sysUserService.getByUsername(username));
    }

    @GetMapping("/mobile/{mobile}")
    public Result<UserAuthDTO> getUserByMobile(@PathVariable String mobile) {
        return Result.success(sysUserService.getByMobilePhone(mobile));
    }


    @GetMapping("/me")
    public Result<UserVO> getCurrentUser() {
        UserVO userVO = new UserVO();
        // 用户基本信息
        Integer userId = JwtUtils.getUserId();
        SysUser user = sysUserService.getById(userId);
        BeanUtil.copyProperties(user, userVO);
        // 用户角色信息
        List<String> roles = JwtUtils.getRoles();
        userVO.setRoles(roles);
        //用户按钮权限信息
        List<String> perms = iSysPermissionService.listBtnPermByRoles(roles);
        userVO.setPerms(perms);
        return Result.success(userVO);
    }

//    @ApiOperation(value = "新增用户")
    @PostMapping
    public Result add(@RequestBody SysUser user) {
        boolean result = sysUserService.save(user);
        return Result.judge(result);
    }


    @GetMapping("/{id}")
    public Result<SysUser> detail(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        if (user != null) {
            List<Long> roleIds = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                    .eq(SysUserRole::getUserId, user.getId())
                    .select(SysUserRole::getRoleId)
            ).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            user.setRoleIds(roleIds);
        }
        return Result.success(user);
    }

    @PutMapping(value = "/{id}")
    public Result<String> update(
            @PathVariable Long id,
            @RequestBody SysUser user) {
        boolean result = sysUserService.updateUser(user);
        return Result.judge(result);
    }

    @DeleteMapping("/{ids}")
    public Result<String> delete(@PathVariable String ids) {
        boolean status = sysUserService.removeByIds(StrUtil.split(ids,",").stream().map(Integer::parseInt).collect(Collectors.toList()));
        return Result.judge(status);
    }

    @PatchMapping(value = "/{id}")
    public Result<String> patch(@PathVariable Long id, @RequestBody SysUser user) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<SysUser>().eq(SysUser::getId, id);
        updateWrapper.set(user.getStatus() != null, SysUser::getStatus, user.getStatus());
        if(StrUtil.isNotBlank(user.getPassword())) {
            updateWrapper.set(StrUtil.isNotBlank(user.getPassword()),SysUser::getPassword,passwordEncoder.encode(user.getPassword()));
        }
        boolean status = sysUserService.update(updateWrapper);
        return Result.judge(status);
    }
}
